package cn.ad.server.web.spring.service.actions.handler;

import cn.ad.server.web.exception.AdServerMessageException;
import cn.ad.server.web.spring.model.sts.STSAdResponse;
import cn.ad.server.domain.ad.AdMaterial;
import cn.ad.server.domain.ad.AdSize;
import cn.ad.server.domain.ad.AdSpace;
import cn.ad.server.domain.ad.Creative;
import cn.ad.server.domain.enumration.MaterialFormat;
import cn.ad.server.domain.enumration.ReturnCode;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Random;

/**
 * @author dongbin.yu
 * @from 2016-06-25
 * @since V1.0
 */
public class VideoAdFormatHandler extends AbstractAdFormatHandler {

	@Override
	public void matchCreative(AdSpace adSpace) {

		if (adSpace.getMatchStrategy() != null) {
			// List<Creative> creativeList =
			// adSpace.getMatchStrategy().getCreatives();
			List<Creative> creativeList = adSpace.getMatchStrategy().getMatchCreatives();
			adSpace.setMatchCreative(creativeList.get(new Random().nextInt(creativeList.size())));
		}
	}

	@Override
	public void compositeMaterial(AdSpace localAdSpace, STSAdResponse.AdSpace adSpace, int os) {

		Creative matchCreative = localAdSpace.getMatchCreative();
		AdMaterial adMaterial = localAdSpace.getMatchAdMaterial();

		// 判断素材为空
		if (adMaterial == null) {
			throw new AdServerMessageException(ReturnCode.E20003);
		}

		// 填充adResponse的adSpace数据
		STSAdResponse.Creative creative = new STSAdResponse.Creative();
		creative.setCid(matchCreative.getId());

		// 填充event
		interactionHandler(matchCreative, creative, os);

		// 填充印象对象
		String impressionTracking = matchCreative.getImpressionTracking();
		if (StringUtils.hasText(impressionTracking)) {
			creative.setImpression(impressionTracking.split("\\|\\|\\|"));
		}

		String clicksTracking = matchCreative.getClicksTracking();
		if (StringUtils.hasText(impressionTracking)) {
			creative.setClick(clicksTracking.split("\\|\\|\\|"));
		}

		// 设置广告位创意
		adSpace.setCreative(new STSAdResponse.Creative[] { creative });

		STSAdResponse.Video video = new STSAdResponse.Video();
		AdSize adSize = adMaterial.getAdSize();
		video.setWidth(adSize.getWidth());
		video.setHeight(adSize.getHeight());
		if (adMaterial.getMaterialFormat() > 0) {
			video.setType(MaterialFormat.materialFormatMap.get(adMaterial.getMaterialFormat()).getName());
		}
		video.setCreativeUrl(adMaterial.getMaterialUrl());
		video.setDuration(adMaterial.getDuration());

		adSpace.getCreative()[0].setVideo(video);

	}
}
